package com.lx.controller;

import com.antherd.smcrypto.sm3.Sm3;
import com.lx.annotation.CheckPermission;
import com.lx.entity.User;
import com.lx.exceptionHandler.NameException;
import com.lx.exceptionHandler.PasswordException;
import com.lx.service.UserService;
import com.lx.util.JwtUtil;
import com.lx.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/api")
@Api(tags = "用户管理接口")
public class UserController{
    @Autowired
    UserService userService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @PostMapping("/user/pageinfo")
    @ApiOperation(value = "分页查询用户列表", notes = "根据条件查询分页列表")
    public Result getPageInfo(@ApiParam(value = "查询参数", required = true) @RequestBody Map<String, Object> params) {
        if (params.containsKey("userName") &&
                (params.get("userName") == null || params.get("userName").toString().isEmpty())) {
            params.remove("userName");
        }

        if (params.containsKey("createTime") &&
                (params.get("createTime") == null || params.get("createTime").toString().isEmpty())) {
            params.remove("createTime");
        }

        return Result.success(5200, "获取pageinfo成功").add("pageinfo", userService.getPageInfo(params));
    }

//    @PostMapping("/user/detail")
//    @ApiOperation(value = "查询用户详情-方案1", notes = "根据用户ID查询用户详情")
//    public Result getUserDetail(@ApiParam(value = "用户ID参数", required = true) @RequestBody Map<String, Object> params) {
//        Object idObj = params.get("id");
//        Integer id = null;
//
//        // 直接处理字符串类型
//        if (idObj instanceof String) {
//            id = Integer.valueOf((String) idObj);
//        } else if (idObj instanceof Integer) {
//            id = (Integer) idObj;
//        }
//
//        if (id == null) {
//            return Result.error().add("msg", "用户ID不能为空");
//        }
//
//        User user = userService.selectById(id);
//        if (user != null) {
//            return Result.success().add("list", user);
//        } else {
//            return Result.error().add("msg", "未找到指定的用户");
//        }
//    }

    @PostMapping("/user/detail")
    public Result getUserDetail(@RequestBody Map<String, Object> params) {
        Integer userId = Integer.parseInt(params.get("userId").toString());
        User user = userService.selectById(userId);
        if (user != null) {
            return Result.success().add("userInfo", user);
        } else {
            return Result.error().add("msg", "未找到指定的用户");
        }
    }

    @PostMapping("/user/find")
    @ApiOperation(value="查询用户详情-方案2", notes ="根据用户登录名查询用户详情")
    public Result getUserByUserName(@ApiParam(value = "用户登录名参数", required = true) @RequestBody Map<String, Object> params) {
        User user = userService.getUserByLoginName(params.get("loginName").toString());
        return user == null ?
                Result.error(5500, "通过用户登录名查询用户失败") :
                Result.success(5200, "通过用户登录名查询用户成功");
    }



    /**
     * 添加用户
     */
    @PostMapping("/user/adduser")
    @ApiOperation(value = "添加用户", notes = "添加新的用户")
    public Result addUser(@ApiParam(value = "用户信息参数", required = true) @RequestBody Map<String, Object> params) {
        // 从参数中提取用户信息
        //先比较验证码是否匹配
       String code = stringRedisTemplate.opsForValue().get(params.get("email").toString());
       if(code == null) return Result.error(5000, "后台校验错误").add("emailValidCode", "验证码无效");
       if(!code.equals(params.get("emailValidCode").toString())) return Result.error(5000, "后台校验错误").add("emailValidCode", "验证码不匹配");
        User user = new User();
        if (params.containsKey("loginName") && params.get("loginName") != null) {
            user.setLoginName(params.get("loginName").toString());
        }

        if (params.containsKey("userName") && params.get("userName") != null) {
            user.setUserName(params.get("userName").toString());
        }

        if (params.containsKey("password") && params.get("password") != null) {
            user.setPassword(Sm3.sm3(params.get("password").toString()));
        }

        if (params.containsKey("sex") && params.get("sex") != null) {
            user.setSex(Integer.parseInt(params.get("sex").toString()));
        }

        if (params.containsKey("identityCode") && params.get("identityCode") != null) {
            user.setIdentityCode(params.get("identityCode").toString());
        }

        if (params.containsKey("email") && params.get("email") != null) {
            user.setEmail(params.get("email").toString());
        }

        if (params.containsKey("mobile") && params.get("mobile") != null) {
            user.setMobile(params.get("mobile").toString());
        }

        boolean result = userService.addUser(user);
        if (result) {
            return Result.success(5200, "添加用户成功");
        } else {
            return Result.error(5500, "添加用户失败");
        }
    }

    /**
     * 更新用户
     */
    @CheckPermission("1")
    @PostMapping("/user/updateuser")
    @ApiOperation(value = "修改用户信息", notes = "修改用户信息")
    public Result updateUser(@ApiParam(value = "用户信息参数", required = true) @RequestBody Map<String, Object> params) {
        User user = new User();
        if (params.containsKey("id") && params.get("id") != null) {
            try {
                user.setId(Integer.parseInt(params.get("id").toString()));
            } catch (NumberFormatException e) {
                return Result.error(5500, "用户ID格式错误");
            }
        } else {
            return Result.error(5500, "用户ID不能为空");
        }

        if (params.containsKey("loginName") && params.get("loginName") != null) {
            user.setLoginName(params.get("loginName").toString());
        }

        if (params.containsKey("userName") && params.get("userName") != null) {
            user.setUserName(params.get("userName").toString());
        }

        if (params.containsKey("password") && params.get("password") != null) {
            user.setPassword(params.get("password").toString());
        }

        if (params.containsKey("sex") && params.get("sex") != null) {
            user.setSex(Integer.parseInt(params.get("sex").toString()));
        }

        if (params.containsKey("identityCode") && params.get("identityCode") != null) {
            user.setIdentityCode(params.get("identityCode").toString());
        }

        if (params.containsKey("email") && params.get("email") != null) {
            user.setEmail(params.get("email").toString());
        }

        if (params.containsKey("mobile") && params.get("mobile") != null) {
            user.setMobile(params.get("mobile").toString());
        }
        if (params.containsKey("type") && params.get("type") != null) {
            user.setType(Integer.parseInt(params.get("type").toString()));
        }

        boolean result = userService.updateUser(user);
        if (result) {
            return Result.success(5200, "更新用户成功").add("user", user);
        } else {
            return Result.error(5500, "更新用户失败");
        }
    }


    @PostMapping("/user/modifyuser")
    public Result ModifyUser(@RequestBody Map<String, Object> params) {
        User user = new User();
        if (params.containsKey("id") && params.get("id") != null) {
            try {
                user.setId(Integer.parseInt(params.get("id").toString()));
            } catch (NumberFormatException e) {
                return Result.error(5500, "用户ID格式错误");
            }
        } else {
            return Result.error(5500, "用户ID不能为空");
        }

        if (params.containsKey("loginName") && params.get("loginName") != null) {
            // 检查登录名是否重复
            User existingUser = userService.getUserByLoginName(params.get("loginName").toString());
            if (existingUser != null && !existingUser.getId().equals(user.getId())) {
                return Result.error(5500, "登录名已存在");
            }
            user.setLoginName(params.get("loginName").toString());
        }

        if (params.containsKey("userName") && params.get("userName") != null) {
            user.setUserName(params.get("userName").toString());
        }

        if (params.containsKey("sex") && params.get("sex") != null) {
            user.setSex(Integer.parseInt(params.get("sex").toString()));
        }

        if (params.containsKey("identityCode") && params.get("identityCode") != null) {
            user.setIdentityCode(params.get("identityCode").toString());
        }

        if (params.containsKey("email") && params.get("email") != null) {
            user.setEmail(params.get("email").toString());
        }

        if (params.containsKey("mobile") && params.get("mobile") != null) {
            user.setMobile(params.get("mobile").toString());
        }

        if (params.containsKey("type") && params.get("type") != null) {
            user.setType(Integer.parseInt(params.get("type").toString()));
        }

        // 获取密码参数
        String oldPassword = params.containsKey("oldPassword") ? params.get("oldPassword").toString() : null;
        String newPassword = params.containsKey("newPassword") ? params.get("newPassword").toString() : null;

        try {
            boolean result = userService.modifyUser(user, oldPassword, newPassword);
            if (result) {
                return Result.success(5200, "更新用户成功");
            } else {
                return Result.error(5500, "更新用户失败");
            }
        } catch (NameException e) {
            return Result.error(5500, e.getMessage());
        } catch (PasswordException e) {
            return Result.error(5500, e.getMessage());
        }
    }

    /**
     * 删除用户
     */
    @CheckPermission("1")
    @PostMapping("/user/delete")
    @ApiOperation(value = "删除用户", notes = "删除用户")
    public Result deleteUser(@ApiParam(value = "用户ID参数", required = true) @RequestBody Map<String, Object> params) {
        try {
            int id = Integer.parseInt(params.get("id").toString());
            boolean result = userService.delUser(id);
            if (result) {
                return Result.success(5200, "删除用户成功");
            } else {
                return Result.error(5500, "删除用户失败");
            }
        } catch (Exception e) {
            return Result.error(5500, "参数错误: " + e.getMessage());
        }
    }

    /**
     * 用户登录
     */
    @PostMapping("/user/login")
    @ApiOperation(value = "用户登录", notes = "用户登录验证")
    public Result login(@ApiParam(value = "登录信息参数", required = true) @RequestBody Map<String, Object> params) {
        String loginName = null, password = null;
        if (params.containsKey("loginName") && !params.get("loginName").toString().isEmpty()) {
            loginName = (String)params.get("loginName");
        }
        if (params.containsKey("password") && !params.get("password").toString().isEmpty()) {
            password = (String)params.get("password");
        }
        if(loginName == null || loginName.isEmpty() || password == null || password.isEmpty()) {
            Result errResult = Result.error(5500, "后台校验错误");
            if(loginName == null || loginName.isEmpty()) errResult.add("loginName", "用户登录名不能为空");
            if(password == null || password.isEmpty()) errResult.add("password", "密码不能为空");
        }
        try{
            Map<String, Object> result = userService.login(loginName, password);
            return Result.success(5200, "用户登录成功！").
                    add("token", result.get("token")).
                    add("loginName", result.get("loginName")).
                    add("type", result.get("type"));
        }catch (NameException e) {
            return Result.error(5500, "用户登录失败！").add("loginName", e.getMessage());
        }catch (PasswordException e) {
            return Result.error(5500, "用户登录失败！").add("password", e.getMessage());
        }
    }


    @PostMapping("/user/getUserId")
    public Result getUserId(String token) {

        return Result.success().add("userId", JwtUtil.getUserID(token));

    }

    @PostMapping("/user/loginout")
    public Result loginOut(HttpServletRequest request) {
        //退出当前用户, 清除redis数据
        String token = request.getHeader("Authorization");
        Integer userId = JwtUtil.getUserID(token);
        stringRedisTemplate.delete(userId.toString());
        return Result.success(5200, "退出登录成功！");
    }


}
